﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StockDataBase.DataOperation
{
    public class DatabaseOp
    {
        public DatabaseOp()
        {
        }

        private SQLiteConnection m_dbConnection;

        //创建一个空的数据库
        //public void CreateNewDatabase(String file)
        //{
        //    SQLiteConnection.CreateFile(file);
        //}

        //创建一个连接到指定数据库
        public void ConnectToDatabase(string file)
        {
            m_dbConnection = new SQLiteConnection("Data Source=" + file + ";Version=3;");
            m_dbConnection.Open();
        }

        //在指定数据库中创建一个table
        public void CreateTable(String tableName, String[] items)
        {
            string sql = "create table " + tableName + " (";

            foreach (var item in items)
            {
                sql += (item + ",");
            }
            sql = sql.Remove(sql.Length - 1, 1);
            sql += ")";

            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();
        }

        DbTransaction trans;
        public void Begin()
        {
            trans = m_dbConnection.BeginTransaction();
        }
        public void End()
        {
            trans.Commit();
        }
        //插入一些数据
        public void ExcuteSql(string sql)
        {
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();

        }

        //使用sql查询语句，并显示结果
        public SQLiteDataReader ExcuteReader(string sql)
        {
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            SQLiteDataReader reader = command.ExecuteReader();
            return reader;
        }
    }

}
